package com.are.odisea;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class SrvConsumoOrden
 */
@WebServlet("/SrvConsumoOrden")
public class SrvConsumoOrden extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SrvConsumoOrden() {
		super();
		// TODO Auto-generated constructor stub
	}

	@SuppressWarnings("unchecked")
	protected void ProcesarPeticion(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=ISO-8859-1");
		PrintWriter out = response.getWriter();
		HttpSession sesion = request.getSession();

		String operacion = (String) request.getParameter("operacion");
		db conexion = null;

		try {
			if (operacion.equals("add")) {
				
				String id = (String)request.getParameter("id");
				String cantidad = (String)request.getParameter("cantidad");
				conexion = new db();
				
				ArrayList<ConsumoOrden> consumos = new ArrayList<ConsumoOrden>();
				if (sesion.getAttribute("consumos") == null) {
					sesion.setAttribute("consumos", consumos);
				}else {
					consumos = (ArrayList<ConsumoOrden>) sesion.getAttribute("consumos");
				}
				
				if (consumos.size() == 0) {
					GestionStock gs = new GestionStock(conexion,null);
					if (gs.FindStockById(id)) {
						Stock stock = gs.getStock();
						ConsumoOrden co = new ConsumoOrden();
						co.setId(stock.getId());
						co.setMaterial(stock.getMaterial());
						co.setBodega(stock.getDesc_bodega());
						co.setUnidad(stock.getUnd_material());
						co.setDescripcion(stock.getDesc_material());
						co.setSuministro(stock.getSuministro());
						co.setCentro(stock.getDesc_centro());
						co.setEstado(stock.getDesc_estado());
						co.setEntrega(stock.getNum_entrega());
						co.setCantidad(Double.parseDouble(cantidad));
						co.setSerial(stock.getSerial());
						co.setCasdid(stock.getCasid());
						consumos.add(co);
						sesion.setAttribute("consumos", consumos);
						out.print("OK");
						
					}else {
						throw new SQLException("Id de Stock no encontrado");
					}
				}else {
					boolean encontrado = false;
					for (int i=0; i < consumos.size(); i++) {
						ConsumoOrden co = consumos.get(i);
						if (co.getId().equals(id)) {
							encontrado = true;
							break;
						}
					}
					
					if (!encontrado) {
						GestionStock gs = new GestionStock(conexion,null);
						if (gs.FindStockById(id)) {
							Stock stock = gs.getStock();
							ConsumoOrden co = new ConsumoOrden();
							co.setId(stock.getId());
							co.setMaterial(stock.getMaterial());
							co.setBodega(stock.getDesc_bodega());
							co.setUnidad(stock.getUnd_material());
							co.setDescripcion(stock.getDesc_material());
							co.setSuministro(stock.getSuministro());
							co.setCentro(stock.getDesc_centro());
							co.setEstado(stock.getDesc_estado());
							co.setEntrega(stock.getNum_entrega());
							co.setCantidad(Double.parseDouble(cantidad));
							co.setSerial(stock.getSerial());
							co.setCasdid(stock.getCasid());
							consumos.add(co);
							sesion.setAttribute("consumos", consumos);
							out.print("OK");
							
						}else {
							throw new SQLException("Id de Stock no encontrado");
						}
					}else {
						out.print("El item de material ya se encuentra agregado");
					}
					
				}

			}
			
			if (operacion.equals("list")) {
				ArrayList<ConsumoOrden> consumos = new ArrayList<ConsumoOrden>();
				if (sesion.getAttribute("consumos") == null) {
					sesion.setAttribute("consumos", consumos);
				}else {
					consumos = (ArrayList<ConsumoOrden>) sesion.getAttribute("consumos");
				}
				out.println("<table>");
				out.println("<tr>");
				out.println("<th>Codigo</th>");
				out.println("<th>Descripcion</th>");
				out.println("<th>Und.</th>");
				out.println("<th>Bodega</th>");
				out.println("<th>Centro</th>");
				out.println("<th>Suministro</th>");
				out.println("<th>Estado</th>");
				out.println("<th>Entrega</th>");
				out.println("<th>Cantidad</th>");
				out.println("<th>Accion</th>");
				out.println("</tr>");
				for (ConsumoOrden co : consumos) {
					out.println("<tr>");
					out.println("<td>" + co.getMaterial() + "</td>");
					out.println("<td>" + co.getDescripcion() + "</td>");
					out.println("<td>" + co.getUnidad() + "</td>");
					out.println("<td>" + co.getBodega() + "</td>");
					out.println("<td>" + co.getCentro() + "</td>");
					out.println("<td>" + co.getSuministro() + "</td>");
					out.println("<td>" + co.getEstado() + "</td>");
					out.println("<td>" + co.getEntrega() + "</td>");
					out.println("<td>" + co.getCantidad() + "</td>");
					out.println("<td><a href=\"javascript:EliminarMaterial('" + co.getId() + "')\">Eliminar</td>");
					
					out.println("</tr>");
				}
				out.println("<tr>");
				out.println("<td colspan='10'>Total registros: " + consumos.size() + "</td>");
				out.println("</tr>");
				out.println("</table>");
			}
			
			
			if (operacion.equals("remove")) {
				
				if (sesion.getAttribute("consumos") != null) {
					ArrayList<ConsumoOrden> consumos = (ArrayList<ConsumoOrden>) sesion.getAttribute("consumos");
					String id = (String)request.getParameter("id");
					boolean eliminado = false;
					for (int i=0; i < consumos.size(); i++) {
						if (consumos.get(i).getId().equals(id)) {
							consumos.remove(i);
							eliminado = true;
							break;
						}
					}
					if (eliminado) {
						out.print("OK");
					}else {
						out.print("Error al eliminar el item");
					}
					
				}else {
					out.print("Error al eliminar el item");
				}
			}
			
			if (operacion.equals("removeAll")) {
				
				if (sesion.getAttribute("consumos") != null) {
					ArrayList<ConsumoOrden> consumos = (ArrayList<ConsumoOrden>) sesion.getAttribute("consumos");
					if (consumos.size() > 0) {
						sesion.setAttribute("consumos", null);
						out.print("OK");
					}else {
						out.print("No hay elementos para eliminar");
					}
				}else {
					out.print("La sesion ha caducado");
				}
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			out.println("Error de conexion. " + e.getMessage());
		} finally {
			if (conexion != null) {
				try {
					conexion.Close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					out.println("Error de conexion. " + e.getMessage());
				}
			}
		}

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.ProcesarPeticion(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.ProcesarPeticion(request, response);
	}

}
